package top.likeqc.blog.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.likeqc.blog.NotFoundException;
import top.likeqc.blog.dao.TypeRepository;
import top.likeqc.blog.pojo.Type;
import top.likeqc.blog.service.TypeService;

import java.util.List;
import java.util.Optional;

/**
 * @author likeqc.top
 * @date 2021/4/16 18:47
 */
@Service
public class TypeServiceImpl implements TypeService {

    @Autowired private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findById(id).get();
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Optional<Type> result = typeRepository.findById(id);
        if (!result.isPresent()) {
            throw new NotFoundException("不存在该类型");
        }
        Type t = result.get();
        BeanUtils.copyProperties(type, t);
        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }
}
